package com.mewp.permissions.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mewp.permissions.common.entity.Result;
import com.mewp.permissions.model.po.SysUser;
import com.mewp.permissions.model.vo.SysUserQueryVo;
import com.mewp.permissions.system.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * @author mewp
 * @version 1.0
 * @date 2023/7/28 10:46
 */
@Api(tags = "用户管理")
@RestController
@RequestMapping("/admin/system/user")
public class SysUserController {
    @Resource
    private SysUserService userService;
    @Resource
    private BCryptPasswordEncoder passwordEncoder;

    @ApiOperation(value = "获取分页列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页码", paramType = "path", required = true),
            @ApiImplicitParam(name = "size", value = "每页记录数", paramType = "path", required = true)
    })
    @GetMapping("/{page}/{size}")
    public Result<Page<SysUser>> index(@PathVariable Integer page, @PathVariable Integer size, SysUserQueryVo userQueryVo) {
        Page<SysUser> pageModel = userService.selectPage(page, size, userQueryVo);
        return Result.ok(pageModel);
    }

    @ApiOperation(value = "获取用户")
    @GetMapping("/{id}")
    public Result<SysUser> get(@PathVariable Long id) {
        SysUser user = userService.getById(id);
        return Result.ok(user);
    }

    @ApiOperation(value = "保存用户")
    @PostMapping("/")
    public Result<Boolean> save(@RequestBody SysUser user) {
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        boolean result = userService.save(user);
        return result ? Result.ok() : Result.fail();
    }

    @ApiOperation(value = "更新用户")
    @PutMapping("/")
    public Result<Boolean> updateById(@RequestBody SysUser user) {
        boolean result = userService.updateById(user);
        return result ? Result.ok() : Result.fail();
    }

    @ApiOperation(value = "删除用户")
    @DeleteMapping("/{id}")
    public Result<Boolean> remove(@PathVariable Long id) {
        boolean result = userService.removeById(id);
        return result ? Result.ok() : Result.fail();
    }

    @ApiOperation(value = "更新状态")
    @GetMapping("status/{id}/{status}")
    public Result<Boolean> updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        boolean result = userService.updateStatus(id, status);
        return result ? Result.ok() : Result.fail();
    }

    public static void main(String[] args) {
        String encode = new BCryptPasswordEncoder().encode("123456");
        System.out.println(encode);
    }
}
